<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="部署时间">
        <el-date-picker v-model="daterangeDepolyTime" style="width: 360px" value-format="yyyy-MM-dd HH:mm:ss"
          type="datetimerange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
      </el-form-item>
      <el-form-item label="流程类型" prop="bpmnType">
        <el-select v-model="queryParams.bpmnType" placeholder="请选择流程类型" clearable>
          <el-option v-for="dict in dict.type.bus_flow_audit_type" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['flow:bpmnInfo:add']">流程定义部署 </el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['flow:bpmnInfo:edit']">修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['flow:bpmnInfo:remove']">删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['flow:bpmnInfo:export']">导出
        </el-button>
      </el-col> -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="bpmnInfoList">
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <!-- <el-table-column label="id主键，唯一标识" align="center" prop="id" /> -->
      <el-table-column label="流程名称" align="center" prop="bpmnLabel" />
      <el-table-column label="流程类型" align="center" prop="bpmnType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.bus_flow_audit_type" :value="scope.row.bpmnType" />
        </template>
      </el-table-column>
      <el-table-column label="流程定义生成的key" align="center" prop="processDefinitionKey" />
      <el-table-column label="部署时间" align="center" prop="depolyTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.depolyTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="版本" align="center" prop="version" />
      <el-table-column label="备注" align="center" prop="info" />
      <el-table-column label="流程文件" align="center" prop="bpmnFile">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="handlePreview(scope.row)" v-hasPermi="['flow:bpmnInfo:edit']">查看
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="流程图" align="center" prop="bpmnImg" >
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="handleImage(scope.row)" v-hasPermi="['flow:bpmnInfo:edit']">查看
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <!-- <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['flow:bpmnInfo:edit']">修改
          </el-button> -->
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['flow:bpmnInfo:remove']">撤销
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改流程定义对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="流程类型" prop="bpmnType">
          <el-select v-model="form.bpmnType" placeholder="请选择流程类型">
            <el-option v-for="dict in dict.type.bus_flow_audit_type" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="流程定义文件" prop="bpmnFile">
          <el-upload ref="upload" :action="uploadUrl" :limit="1" :on-change="handleChange"
            :before-upload="handleBeforeUpload" :file-list="fileList" :auto-upload="false">
            <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
            <!-- <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button> -->
            <div slot="tip" class="el-upload__tip">只能上传bpmn/zip文件,且不超过5Mb</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="备注" prop="info">
          <el-input type="textarea" v-model="form.info" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 预览界面 -->
    <el-dialog :title="preview.title" :visible.sync="preview.open" width="80%" top="5vh" append-to-body class="scrollbar">
      <pre><code class="hljs" v-html="highlightedCode('xml')"></code></pre>
    </el-dialog>
    <!-- 预览界面 -->
    <el-dialog :title="bpmnImage.title" :visible.sync="bpmnImage.open" width="80%" top="5vh" append-to-body class="scrollbar">
     <img :src="bpmnImage.data">
    </el-dialog>
  </div>
</template>

<script>
import { listBpmnInfo, getBpmnInfo, delBpmnInfo, addBpmnInfo, updateBpmnInfo, deployBpmn, getBpmnFile } from "@/api/flow/bpmnInfo";
import hljs from "highlight.js/lib/highlight";
import "highlight.js/styles/github-gist.css";
hljs.registerLanguage("xml", require("highlight.js/lib/languages/xml"));

export default {
  name: "BpmnInfo",
  dicts: ['bus_flow_audit_type'],
  data() {
    return {
      //流程图
      bpmnImage:{
        title:'流程定义图',
        open:false,
        data:null,
      },
      //预览弹窗
      preview: {
        title: '流程文件',
        open: false,
        code: '<h1>是一个测试的代码块<hi>'
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 流程定义表格数据
      bpmnInfoList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 备注时间范围
      daterangeDepolyTime: [],
      //文件上传路径
      uploadUrl: '',
      //文件上传列表
      fileList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        bpmnType: null,
        depolyTime: null,
      },
      // 表单参数
      form: {
        bpmnFile: null,
        fileType: null,
        info: null
      },
      // 表单校验
      rules: {
        bpmnType: [
          { required: true, message: "请选择审核类型", trigger: "changer" }
        ],
        info: [
          { required: true, message: "请输入备注信息", trigger: "biur" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询流程定义列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeDepolyTime && '' != this.daterangeDepolyTime) {
        this.queryParams.params["beginDepolyTime"] = this.daterangeDepolyTime[0];
        this.queryParams.params["endDepolyTime"] = this.daterangeDepolyTime[1];
      }
      listBpmnInfo(this.queryParams).then(response => {
        this.bpmnInfoList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        bpmnLabel: null,
        bpmnType: null,
        processDefinitionKey: null,
        depolyTime: null,
        version: null,
        info: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeDepolyTime = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加流程定义";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getBpmnInfo(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改流程定义";
      });
    },
    /** 提交按钮 */
    submitForm() {

      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.fileList.length === 0) {
            this.$modal.msgError('请选择部署文件');
            return false;
          }
          if (!this.handleBeforeUpload(this.fileList[0])) {
            return false;
          }
          deployBpmn({ ...this.form, bpmnFile: this.fileList[0].raw }).then(() => {
            this.$modal.msgSuccess('部署流程定义成功');
            this.open = false;
            this.getList();
          });
        }
      });
    },
    /** 撤销按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认撤销流程定义编号为"' + ids + '"的数据项？').then(function () {
        return delBpmnInfo(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("撤销成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('flow/bpmnInfo/export', {
        ...this.queryParams
      }, `bpmnInfo_${new Date().getTime()}.xlsx`)
    },
    //校验上传的文件
    handleBeforeUpload(file) {
      let fileNameArr = file.name.split('.');
      let fileExt = fileNameArr[fileNameArr.length - 1];
      if (['zip', 'bpmn', 'xml'].indexOf(fileExt) < 0) {
        this.$modal.msgError('文件类型不匹配');
        return false;
      }
      return true;
    },
    //文件改变时调用的函数
    handleChange(file, fileList) {
      this.fileList = fileList;
    },
    /** 高亮显示 */
    highlightedCode(language) {
      const result = hljs.highlight(language, this.preview.code || "", true);
      return result.value || '&nbsp;';
    },
    //查看流程文件
    handlePreview(row) {
      getBpmnFile(row.id, 'xml').then(response => {
        this.preview.code = response;
        this.preview.open = true;
      })
    },
    //查看流程文件图片
    handleImage(row) {
      getBpmnFile(row.id, 'image').then(response => {
        this.bpmnImage.data = response;
        this.bpmnImage.open = true;
      })
    },
  }
};
</script>
